﻿using CBS.APP;
using CBS.Model.UIModel;
using CBS.Model.ViewModel;
using DocumentFormat.OpenXml.Office2013.Word;
using MathNet.Numerics.Distributions;
using NPOI.POIFS.Properties;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CBS.Desktop.FormPage
{
    /// <summary>
    /// CheckStudentSignDetail.xaml 的交互逻辑
    /// </summary>
    public partial class CheckStudentSignDetail : Window, INotifyPropertyChanged
    {
        private bool _isSemesterDataBound = false;
        private bool _isGradeDataBound = false;
        private bool _isClassDataBound = false;
        private bool _isCourseDataBound = false;

        public int _selectedCount;
        public int SelectedCount
        {
            get { return _selectedCount; }
            set
            {
                if (_selectedCount != value)
                {
                    _selectedCount = value;
                    OnPropertyChanged(nameof(SelectedCount)); // 通知属性变化
                }
            }
        }


        private ImportStudentSignDetailFormCondition _formCondition;
        public CheckStudentSignDetail(ImportStudentSignDetailFormCondition formCondition)
        {
            InitializeComponent();

            _formCondition = formCondition;
            DataContext = this;
            LoadCondation();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }


        private async void LoadCondation()
        {
            // 加载 ComboBox 数据
            await LoadDataAsync();

            // 查询 Grid 数据
            BindLesson();
        }

        private async Task LoadDataAsync()
        {
            // 使用 Task.WhenAll 等待所有 ComboBox 数据加载完成
            var tasks = new List<Task>
            {
                BindSemester(),
                BindGrade(),
                BindClass(),
                BindCourse()
            };

            await Task.WhenAll(tasks);
        }

        private async Task BindSemester()
        {
            try
            {
                var list = await Task.Run(() => SemesterApp.GetSelectList());

                if (list.Count == 0)
                {
                    return;
                }


                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Semester.ItemsSource = list;

                }));
                if (this._formCondition == null)
                {
                    cb_Semester.SelectedIndex = 0;
                }
                else
                {
                    int index = cb_Semester.Items
                                            .Cast<SemesterSelectModel>()
                                            .ToList()
                                            .FindIndex(item => item.SemesterId == this._formCondition.SemesterId);

                    cb_Semester.SelectedIndex = index;
                }

                // 设置标志为 true
                _isSemesterDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async Task BindGrade()
        {
            try
            {
                var list = await Task.Run(() => GradeApp.GetSelectList());

                list.Insert(0, new GradeViewModel { GradeId = 0, GradeName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Grade.ItemsSource = list;
                }));
                if (this._formCondition == null)
                {
                    cb_Grade.SelectedIndex = 0;
                }
                else
                {
                    int index = cb_Grade.Items
                                            .Cast<GradeViewModel>()
                                            .ToList()
                                            .FindIndex(item => item.GradeId == this._formCondition.GradeId);

                    cb_Grade.SelectedIndex = index;
                }
                // 设置标志为 true
                _isGradeDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindClass()
        {
            try
            {
                var list = await Task.Run(() => ClassApp.GetSelectList());

                list.Insert(0, new ClassViewModel { ClassId = 0, ClassName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Class.ItemsSource = list;
                }));
                if (this._formCondition == null)
                {
                    cb_Class.SelectedIndex = 0;
                }
                else
                {
                    int index = cb_Class.Items
                                            .Cast<ClassViewModel>()
                                            .ToList()
                                            .FindIndex(item => item.ClassId == this._formCondition.ClassId);

                    cb_Class.SelectedIndex = index;
                }


                // 设置标志为 true
                _isClassDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindCourse()
        {
            try
            {
                var list = await Task.Run(() => CourseApp.GetSelectList());

                list.Insert(0, new CourseViewModel { CourseId = 0, CourseName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Course.ItemsSource = list;

                }));
                if (this._formCondition == null)
                {
                    cb_Course.SelectedIndex = 0;
                }
                else
                {
                    int index = cb_Course.Items
                                            .Cast<CourseViewModel>()
                                            .ToList()
                                            .FindIndex(item => item.CourseId == this._formCondition.CourseId);

                    cb_Course.SelectedIndex = index;
                }


                // 设置标志为 true
                _isCourseDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void BindLesson()
        {
            try
            {
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int gradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                int classId = ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                int courseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId;
                var list = await Task.Run(() => LessonApp.GetSelectList(semesterId, gradeId, classId, courseId));

                if (list.Count == 0)
                {
                    return;
                }

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Lesson.ItemsSource = list;
                }));
                if (this._formCondition == null)
                {
                    cb_Lesson.SelectedIndex = 0;
                }
                else
                {
                    int index = cb_Lesson.Items
                                            .Cast<LessonSelectModel>()
                                            .ToList()
                                            .FindIndex(item => item.LessonId == this._formCondition.LessonId);
                    cb_Lesson.SelectedIndex = (index == -1 ? 0 : index);
                }

                ReloadSelectStudentList();

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void cb_Semester_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isSemesterDataBound)
                return;

            BindLesson();
        }

        private void cb_Grade_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isGradeDataBound)
                return;

            BindLesson();
        }
        private void cb_Class_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isClassDataBound)
                return;

            BindLesson();
        }
        private void cb_Course_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isCourseDataBound)
                return;

            BindLesson();
        }

        //public ObservableCollection<ObservableStudent> SelectStudentList { get; set; } = new ObservableCollection<ObservableStudent>();
        private void ReloadSelectStudentList()
        {
            wp_SelectStudentList.Children.Clear();

            int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
            int gradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
            int classId = ((ClassViewModel)cb_Class.SelectedItem).ClassId;
            int courseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId;

            var data = StudentSignUpApp.GetSignUpStudentList(semesterId, gradeId, classId, courseId);
            var SelectStudentList = new ObservableCollection<ObservableStudent>(data.Select(t => new ObservableStudent { StudentId = t.StudentId, StudentName = t.StudentName, IsChecked = false }).ToList());

            foreach (var item in SelectStudentList)
            {
                var checkBox = new CheckBox
                {
                    Content = item.StudentName,
                    FontSize = 18,
                    Margin = new Thickness(10, 3, 10, 3),
                    Width = 100,
                    DataContext = item // 将学生对象作为数据上下文
                };
                // 绑定复选框的选中状态
                checkBox.SetBinding(CheckBox.IsCheckedProperty, "IsChecked");

                // 绑定 Checked 和 Unchecked 事件
                checkBox.Checked += CheckBox_Checked;
                checkBox.Unchecked += CheckBox_Unchecked;

                // 将复选框添加到 WrapPanel
                wp_SelectStudentList.Children.Add(checkBox);
            }

        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            // 处理选中事件
            var checkBox = sender as CheckBox;
            if (checkBox != null)
            {
                var student = checkBox.DataContext as ObservableStudent;
                if (student != null)
                {
                    student.IsChecked = true; // 更新学生的选中状态
                    SelectedCount++;
                }
            }
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            // 处理取消选中事件
            var checkBox = sender as CheckBox;
            if (checkBox != null)
            {
                var student = checkBox.DataContext as ObservableStudent;
                if (student != null)
                {
                    student.IsChecked = false; // 更新学生的选中状态
                    SelectedCount--;
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Mouse.OverrideCursor = Cursors.Wait;

            int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
            int lessonId = ((LessonSelectModel)cb_Lesson.SelectedItem).LessonId;
            List<int> studentIds = GetSelectedIds();

            try
            {
                if (StudentSignInApp.SelectedStudentSignIn(semesterId, lessonId, studentIds, out string msg))
                {

                    this.DialogResult = true;
                }
                else
                {
                    throw new Exception(msg);
                }

                Mouse.OverrideCursor = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "操作失败", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // 获取选中的 ID
        private List<int> GetSelectedIds()
        {
            var selectedIds = new List<int>();
            foreach (var child in wp_SelectStudentList.Children)
            {
                if (child is CheckBox checkBox && checkBox.IsChecked == true)
                {
                    // 获取绑定的学生对象
                    var student = checkBox.DataContext as ObservableStudent;
                    if (student != null)
                    {
                        selectedIds.Add(student.StudentId);
                    }
                }
            }
            return selectedIds;
        }

    }
}
